package com.crashcollection.util.ftp;

import java.io.File;
import java.util.ArrayList;

import com.crashcollection.configure.Configure;
import com.crashcollection.lib.CrashHandler;
import com.crashcollection.util.file.FileHelper;
import com.crashcollection.util.file.FileInfoBean;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * log文件上传 IntentServer
 * @author Zhongdaxia 2013年8月12日 17:11:37
 *
 */

public class UploadFileService extends IntentService {
	
	public String path =  "";
	
	static int limit = 0;     // 上传最大文件数    
	
	public UploadFileService() {
		super("UploadFileService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		
		// 网络不可用
		if (!isOnline(this)) {
			return; 
		}
		
		// wifi状态
		if (isWifiConn(this)) {
			limit = -1;
		} else {
			limit = 2;
		}
		
		// 目录遍历
		FileHelper fileHelper = new FileHelper(this);
		fileHelper.getFileList(CrashHandler.BasePath,"*.log",null, null);
	}
	
	/**
	 * 遍历指定目录 - 获取文件列表后 - 执行上传函数
	 * @param list
	 */
	public static void UpLoadFile(ArrayList<FileInfoBean> list)
	{
		if(null != list)
		{
			int size = list.size();
			// wifi状态上传所有
			if(limit == -1)
			{
				limit = size;
			}
			// 非wifi状态
			else
			{
				// 最大上传2
				if(limit > list.size())
				{
					limit = size;
				}
			}
			
			for(int i = 0 ; i < list.size() ; i++)
			{
				Ftp ftp=new Ftp();
				
				ftp.ftpUpload(Configure.FTP_host,  Configure.FTP_port, Configure.FTP_username, Configure.FTP_psw, Configure.FTP_remote, Configure.FTP_local, list.get(i).filename);
				try {
					String path = Configure.FTP_local + list.get(i).filename;
					File file = new File(path);
					if(file.exists())
					{
						file.delete();
					}
				} catch (Exception ex) {
				}
			}
		}
	}

	/**
	 * 是否联网
	 * @param context
	 * @return
	 */
	private boolean isOnline(Context context) {
		ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		return (networkInfo != null && networkInfo.isConnected());
	}

	/**
	 * 是否wifi
	 * @param context
	 * @return
	 */
	private boolean isWifiConn(Context context) {
		ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		return networkInfo.isConnected();
	}

}
